package com.starwalking.starwalkingaiagent.demo.invoke;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.starwalking.starwalkingaiagent.demo.TestApiKey;

import java.util.*;

/**
 * DashScope 通义千问 API 简易客户端（hutool 版）
 */
public class HttpAiClient {

    /** 接口地址 */
    private static final String API_URL =
            "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    /** 从环境变量读取，也可以手动写死 */
    private static final String API_KEY = TestApiKey.API_KEY;

    /**
     * 简易对话方法
     * @param userQuestion 用户问题
     * @return AI 回答文本
     */
    public static String chat(String userQuestion) {
        // 1. 构造请求体
        Map<String, Object> request = new HashMap<>();
        request.put("model", "qwen-plus");

        List<Map<String, String>> messages = new ArrayList<>();
        messages.add(createMessage("system", "You are a helpful assistant."));
        messages.add(createMessage("user", userQuestion));

        request.put("input", Collections.singletonMap("messages", messages));
        request.put("parameters", Collections.singletonMap("result_format", "message"));

        String jsonBody = JSONUtil.toJsonStr(request);

        // 2. 发送 POST
        HttpResponse resp = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + API_KEY)
                .header("Content-Type", "application/json")
                .body(jsonBody)
                .execute();

        if (!resp.isOk()) {
            throw new RuntimeException("HttpCode=" + resp.getStatus() + ", body=" + resp.body());
        }

        // 3. 解析回答
        Map<String, Object> result = JSONUtil.toBean(resp.body(),
                new TypeReference<Map<String, Object>>() {}, true);

        List<Map<String, Object>> choices =
                (List<Map<String, Object>>)
                        ((Map<String, Object>) result.get("output")).get("choices");

        return (String) ((Map<String, Object>) choices.get(0).get("message")).get("content");
    }

    private static Map<String, String> createMessage(String role, String content) {
        Map<String, String> msg = new HashMap<>();
        msg.put("role", role);
        msg.put("content", content);
        return msg;
    }

    /* 简单测试 */
    public static void main(String[] args) {
        String answer = chat("解释国庆节的由来？");
        System.out.println("AI 回答：" + answer);
    }
}